package com.ljj.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljj.eduservice.entity.EduSubject;
import com.ljj.eduservice.entity.excel.SubjectData;
import com.ljj.eduservice.service.EduSubjectService;

import java.util.Map;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService subjectService;
    public SubjectExcelListener(){ }
    public SubjectExcelListener(EduSubjectService subjectService){
        this.subjectService = subjectService;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("***"+headMap);
    }
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        System.out.println(subjectData.getOneSubjectName()+"-"+subjectData.getTwoSubjectName());
        if(subjectData == null){
            //TODO:没有数据，抛出异常
        }
        EduSubject oneSubject = existEduSubject(subjectData.getOneSubjectName(),"0");
        if(oneSubject==null){
            //添加一级分类到数据库
            oneSubject = new EduSubject();
            oneSubject.setTitle(subjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            subjectService.save(oneSubject);
        }

        String pid = oneSubject.getId();

        EduSubject twoSubject = existEduSubject(subjectData.getTwoSubjectName(),pid);
        if(twoSubject==null){
            //添加二级分类到数据库
            twoSubject = new EduSubject();
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            twoSubject.setParentId(pid);
            subjectService.save(twoSubject);
        }
    }

    private EduSubject existEduSubject(String title,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper();
        wrapper.eq("title",title);
        wrapper.eq("parent_id",pid);
        EduSubject eduSubject = eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("***************读取完成***************");
    }
}
